package com.shxc.smarttrade.old.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.bean.BankCard;
import com.shxc.smarttrade.old.bean.BankCardInfo;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.CommonDialog;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/6/6.
 */

public class WithdrawDepositActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_have_money)
    TextView tvHaveMoney;
    @BindView(R.id.tv_excharge_rate)
    TextView tvExchargeRate;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_conversion)
    TextView tvConversion;
    @BindView(R.id.tv_waring)
    TextView tvWaring;
    @BindView(R.id.ll_card)
    LinearLayout llCard;
    @BindView(R.id.tv_card_name)
    TextView tvCardName;
    @BindView(R.id.tv_card_num)
    TextView tvCardNum;

    private double money = 0;
    private double rate = 0;
//    private double rmbAmount=

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    double[] result = (double[]) msg.obj;
                    rate = result[1];
                    tvHaveMoney.setText("$ " + BaseUtils.getDigitsData(result[0], 2));
                    tvExchargeRate.setText("(当前汇率：1美元=" + result[1] + "人民币)");
                    break;
                case 1:
                    BankCardInfo bci = (BankCardInfo) msg.obj;
                    if (bci.getErr_code().equals("0")) {

                        if (bci.getData().getCardInfo().size() > 0) {
                            //直接提现
                            showShortDialog();
                            confirmWithdraw(SpUtils.getInt(WithdrawDepositActivity.this, "userId"), money);
                        } else {
                            //跳转到绑定银行卡界面
                            startActivity(new Intent(WithdrawDepositActivity.this, BindBankActivity.class));
                        }
                    } else {
                        showToast(bci.getErr_msg());
                    }
                    break;
                case 2:
                    Intent intent = new Intent(WithdrawDepositActivity.this, WithdrawResultActivity.class);
                    intent.putExtra("rmbAmount", Arith.round4(Arith.mul(money, rate), 2));
                    intent.putExtra("dollar", money);
                    intent.putExtra("rate", rate);
                    intent.putExtra("status", 0);
                    startActivity(intent);
                    finish();
                    break;
                case 3:
                    BankCard bankCard = (BankCard) msg.obj;
                    if (bankCard.getErr_code().equals("0")) {
                        List<BankCard.DataBean.CardInfoBean> cardList = bankCard.getData().getCardInfo();
                        if (cardList.size() > 0) {
                            BankCard.DataBean.CardInfoBean cb = cardList.get(0);
                            tvCardName.setText(cb.getBankName());
                            tvCardNum.setText("卡号：" + cb.getCardNo());
                            llCard.setVisibility(View.VISIBLE);
                        }

                    } else {
                        showToast(bankCard.getErr_msg());
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw_deposit);
        EventBus.getDefault().register(this);
        initView();
        showShortDialog();
        initData(SpUtils.getInt(this, "userId"));//获取汇率等基本数据
        getCardList(SpUtils.getInt(this, "userId"));
        initListener();
    }


    /**
     * 初始化View
     */
    private void initView() {
        tvCenter.setText("提现");
        tvRight.setText("提现记录");
    }

    /**
     * 初始化文本框监听器
     */
    private void initListener() {
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = etMoney.getText().toString();
                if (TextUtils.isEmpty(text)) return;

                try {
                    money = Double.parseDouble(text);
                    if (money < 20) {
                        money = 0;
                        tvConversion.setText("最低20.00美元起提！");
                    } else {
                        tvConversion.setText("折合人民币约：" + Arith.round4(Arith.mul(money, rate), 2) + "元");
                    }
                } catch (Exception e) {
                    tvConversion.setText("请输入正确金额");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    /**
     * 初始化数据
     */
    private void initData(int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId + "");
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.WITHDRAW_DEPOSIT_ACTIVITY_TOWITHDRAW, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
//                Log.e("response", response);
                if (response != null) {
                    JsonObject jsonOb = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonOb.get("err_code").isJsonNull())
                        errCode = jsonOb.get("err_code").getAsString();
                    if (!jsonOb.get("err_msg").isJsonNull())
                        errMsg = jsonOb.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        if (!jsonOb.get("data").isJsonNull()) {
                            JsonObject data = jsonOb.get("data").getAsJsonObject();
                            double amount = 0;
                            double rate = 0;
                            if (!data.get("amount").isJsonNull())
                                amount = data.get("amount").getAsDouble();
                            if (!data.get("rate").isJsonNull())
                                rate = data.get("rate").getAsDouble();
                            double[] two = new double[]{amount, rate};
                            Message msg = Message.obtain();
                            msg.what = 0;
                            msg.obj = two;
                            handler.sendMessage(msg);

                        } else {
                            showToast("数据异常");
                        }

                    } else if (errCode.equals("-5")) {
                        tvWaring.setText(errMsg);
                    } else {
                        showToast(errMsg);
                    }
                } else {
                    showToast("数据异常");
                }
                dismissShortDialog();
            }
        });

    }

    /**
     * 获取银行卡信息
     *
     * @param userId
     */
    private void getCardList(int userId) {
        final Map<String, Object> map = new HashMap<>();
        map.put("userId", userId + "");
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.WITHDRAW_CARD_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    BankCard bankCard = gson.fromJson(response, BankCard.class);
                    Message msg = Message.obtain();
                    msg.what = 3;
                    msg.obj = bankCard;
                    handler.sendMessage(msg);

                }
            }
        });
    }

    @OnClick(R.id.rl_left)
    public void onRlLeftClicked() {
        finish();
    }

    @OnClick(R.id.tv_right)
    public void onTVRightClicked() {
        Intent intent = new Intent(this, AccountInfomationActivity.class);
        intent.putExtra("type", 2);
        startActivity(intent);
    }

    @OnClick(R.id.btn_next)
    public void onBtnNextClicked() {
        if (money > 0) {
            //先判断有无添加银行卡
            CommonDialog commonDialog = new CommonDialog(this, R.style.customDialogStyle);
            commonDialog.setCanceledOnTouchOutside(true);
            commonDialog.setBaseText("提示", "再次确认是否提现", "取消", "确定");
            commonDialog.setYesCLickRunAble(new Runnable() {
                @Override
                public void run() {
                    showShortDialog();
                    getBankInfo(SpUtils.getInt(WithdrawDepositActivity.this, "userId"));
                }
            });
            commonDialog.show();
        } else showToast("请按要求输入金额");
    }

    /**
     * 提现
     *
     * @param userId
     * @param amount
     */
    private void confirmWithdraw(int userId, double amount) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        map.put("amount", amount + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.WITHDRAW_DEPOSIT_ACTIVITY_CONFIRMWITHDRAW, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    } else
                        showToast(errMsg);

                } else {
                    showToast("数据异常");
                }
                dismissShortDialog();
            }
        });
    }

    /**
     * 获取绑定的银行卡信息
     *
     * @param userId
     */
    private void getBankInfo(int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.WITHDRAW_DEPOSIT_ACTIVITY_CARD_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    BankCardInfo bankCardInfo = gson.fromJson(response, BankCardInfo.class);
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = bankCardInfo;
                    handler.sendMessage(msg);
                }
                dismissShortDialog();
            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.BIND_BANK_SUCCESS)) {
            getBankInfo(SpUtils.getInt(this, "userId"));
        }
    }

}
